var express = require('express');
var router = express.Router();
var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;
var User = require('../utils/models').User;

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
    function(username, password, done){
      User.findOne({username: username}, 'username password realname', function(err, user){
        if (err) { return done(err);}
        if (! user) {
          return done(null, false, {message: "Incorrect username."});
        }
        if (user.password != password) {
          return done(null, false, {message: "Incorrect password."});
        }
        return done(null, user);
      });
    }
));

/* GET users listing. */
router.get('/', function(req, res, next) {
  // res.send('respond with a resource');
  res.render("login")
});

//router.all('/login', passport.authenticate('local'), function(req, res, next){
//  if (! req.user) {
//    res.redirect("/users");
//  }
//  req.session.user = req.user;
//  res.redirect('/workstation');
//  //res.render("workstation", {user: req.user});
//});

router.all('/login', function(req, res, next){
  passport.authenticate('local', function(err, user, info){
    if (err) { return next(err); }
    if (!user) { return res.redirect("/users"); }
    req.logIn(user, function(err){
      if (err) { return next(err); }
      req.session.user = user;
      return res.redirect('/workstation');
    });
  })(req, res, next);
});

router.all('/logout', function(req, res, next){
  req.logout();
  req.session.destroy();
  res.set('Content-Type', 'application/json');
  res.status(200).json({'code': 0});
});

module.exports = router;
